<template>
	<div class="diy_edit page_homestay_orders" id="homestay_orders_edit">
		<div class='warp'>
			<div class='container'>
				<div class='row diy_edit_content_box'>
						<div v-if="$check_field('set','merchant_users') || $check_field('add','merchant_users') || $check_field('get','merchant_users')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								商家用户:
							</span>
						</div>
						<div class="diy_field diy_down">
							<select id="form_merchant_users" :disabled="disabledObj['merchant_users_isDisabled']" v-model="form['merchant_users']" v-if="(form['merchant_users'] && $check_field('set','merchant_users')) || (!form['merchant_users'] && $check_field('add','merchant_users'))" >
								<option v-for="o in list_user_merchant_users" :value="o['user_id']">
									{{o['nickname'] + '-' + o['username']}}
								</option>
							</select>
							<span v-else-if="$check_field('get','merchant_users')">{{ get_user_info("merchant_users", form['merchant_users']) }}</span>
						</div>
					</div>
							<div v-if="$check_field('set','name_of_homestay') || $check_field('add','name_of_homestay') || $check_field('get','name_of_homestay')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								民宿名称:
							</span>
						</div>
								<!-- 文本 -->
									<div class="diy_field diy_text">
							<input type="text" id="form_name_of_homestay" v-model="form['name_of_homestay']" placeholder="请输入民宿名称" v-if="(form['name_of_homestay'] && $check_field('set','name_of_homestay')) || (!form['name_of_homestay'] && $check_field('add','name_of_homestay'))"  :disabled="disabledObj['name_of_homestay_isDisabled']"/>
							<span v-else-if="$check_field('get','name_of_homestay')">{{ form['name_of_homestay'] }}</span>
						</div>
										</div>
							<div v-if="$check_field('set','types_of_homestays') || $check_field('add','types_of_homestays') || $check_field('get','types_of_homestays')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								民宿类型:
							</span>
						</div>
								<!-- 文本 -->
									<div class="diy_field diy_text">
							<input type="text" id="form_types_of_homestays" v-model="form['types_of_homestays']" placeholder="请输入民宿类型" v-if="(form['types_of_homestays'] && $check_field('set','types_of_homestays')) || (!form['types_of_homestays'] && $check_field('add','types_of_homestays'))"  :disabled="disabledObj['types_of_homestays_isDisabled']"/>
							<span v-else-if="$check_field('get','types_of_homestays')">{{ form['types_of_homestays'] }}</span>
						</div>
										</div>
							<div v-if="$check_field('set','homestay_deposit') || $check_field('add','homestay_deposit') || $check_field('get','homestay_deposit')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								民宿押金:
							</span>
						</div>
								<!-- 数字 -->
						<div class="diy_field diy_number">
							<input type="number" id="form_homestay_deposit" v-model.number="form['homestay_deposit']" placeholder="请输入民宿押金" v-if="(form['homestay_deposit'] && $check_field('set','homestay_deposit')) || (!form['homestay_deposit'] && $check_field('add','homestay_deposit'))" :disabled="disabledObj['homestay_deposit_isDisabled']" />
							<span v-else-if="$check_field('get','homestay_deposit')">{{ form['homestay_deposit'] }}</span>
						</div>
							</div>
							<div v-if="$check_field('set','daily_price_of_homestay') || $check_field('add','daily_price_of_homestay') || $check_field('get','daily_price_of_homestay')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								民宿日价:
							</span>
						</div>
								<!-- 数字 -->
						<div class="diy_field diy_number">
							<input type="number" id="form_daily_price_of_homestay" v-model.number="form['daily_price_of_homestay']" placeholder="请输入民宿日价" v-if="(form['daily_price_of_homestay'] && $check_field('set','daily_price_of_homestay')) || (!form['daily_price_of_homestay'] && $check_field('add','daily_price_of_homestay'))" :disabled="disabledObj['daily_price_of_homestay_isDisabled']" />
							<span v-else-if="$check_field('get','daily_price_of_homestay')">{{ form['daily_price_of_homestay'] }}</span>
						</div>
							</div>
							<div v-if="$check_field('set','ordinary_users') || $check_field('add','ordinary_users') || $check_field('get','ordinary_users')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								普通用户:
							</span>
						</div>
						<div class="diy_field diy_down">
							<select id="form_ordinary_users" :disabled="disabledObj['ordinary_users_isDisabled']" v-model="form['ordinary_users']" v-if="(form['ordinary_users'] && $check_field('set','ordinary_users')) || (!form['ordinary_users'] && $check_field('add','ordinary_users'))" >
								<option v-for="o in list_user_ordinary_users" :value="o['user_id']">
									{{o['nickname'] + '-' + o['username']}}
								</option>
							</select>
							<span v-else-if="$check_field('get','ordinary_users')">{{ get_user_info("ordinary_users", form['ordinary_users']) }}</span>
						</div>
					</div>
							<div v-if="$check_field('set','user_name') || $check_field('add','user_name') || $check_field('get','user_name')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								用户姓名:
							</span>
						</div>
								<!-- 文本 -->
									<div class="diy_field diy_text">
							<input type="text" id="form_user_name" v-model="form['user_name']" placeholder="请输入用户姓名" v-if="(form['user_name'] && $check_field('set','user_name')) || (!form['user_name'] && $check_field('add','user_name'))"  :disabled="disabledObj['user_name_isDisabled']"/>
							<span v-else-if="$check_field('get','user_name')">{{ form['user_name'] }}</span>
						</div>
										</div>
							<div v-if="$check_field('set','time_of_appointment') || $check_field('add','time_of_appointment') || $check_field('get','time_of_appointment')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								预约时间:
							</span>
						</div>
								<!-- 日期 -->
						<div class="diy_field diy_date">
							<input type="date" :disabled="disabledObj['time_of_appointment_isDisabled']" id="form_time_of_appointment" v-model="form['time_of_appointment']" placeholder="请输入预约时间" v-if="(form['time_of_appointment'] && $check_field('set','time_of_appointment')) || (!form['time_of_appointment'] && $check_field('add','time_of_appointment'))"/>
							<span v-else-if="$check_field('get','time_of_appointment')">{{ form['time_of_appointment'] }}</span>
						</div>
							</div>
							<div v-if="$check_field('set','appointment_days') || $check_field('add','appointment_days') || $check_field('get','appointment_days')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								预约天数:
							</span>
						</div>
								<!-- 数字 -->
						<div class="diy_field diy_number">
							<input type="number" id="form_appointment_days" v-model.number="form['appointment_days']" placeholder="请输入预约天数" v-if="(form['appointment_days'] && $check_field('set','appointment_days')) || (!form['appointment_days'] && $check_field('add','appointment_days'))" :disabled="disabledObj['appointment_days_isDisabled']" />
							<span v-else-if="$check_field('get','appointment_days')">{{ form['appointment_days'] }}</span>
						</div>
							</div>
							<div v-if="$check_field('set','total_cost') || $check_field('add','total_cost') || $check_field('get','total_cost')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								费用总计:
							</span>
						</div>
								<!-- 计算 -->
						<div class="diy_field diy_compute">
							<span v-if="$check_field('get','total_cost')">{{ toFixed(form['daily_price_of_homestay'] * form['appointment_days']) }}</span>
						</div>
          </div>





				</div>
				<div class="diy_edit_submit_box row">
					<div class="col-12">
						<div class="btn_box">
							<button class="btn_submit" @click="submit()">提交</button>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import mixin from "@/mixins/page.js";
	export default {
		mixins: [mixin],
		components: {},
		data() {
			return {
				url_get_obj: "~/api/homestay_orders/get_obj?",
				url_add: "~/api/homestay_orders/add?",
				url_set: "~/api/homestay_orders/set?",

				// 登录权限
				oauth: {
					"signIn": true,
					"user_group": []
				},

				// 查询条件
				query: {
          "merchant_users": 0,
          "name_of_homestay": "",
          "types_of_homestays": "",
          "homestay_deposit": 0,
          "daily_price_of_homestay": 0,
          "ordinary_users": 0,
          "user_name": "",
          "time_of_appointment": "",
          "appointment_days": 0,
          "total_cost": 0,
          "homestay_orders_id": 0,
				},

				obj: {
          "merchant_users": 0, // 商家用户
          "name_of_homestay":  '', // 民宿名称
          "types_of_homestays":  '', // 民宿类型
          "homestay_deposit":  0, // 民宿押金
          "homestay_deposit_state":"",
          "daily_price_of_homestay":  0, // 民宿日价
          "ordinary_users": 0, // 普通用户
          "user_name":  '', // 用户姓名
          "time_of_appointment": new Date().getTime(),
          "appointment_days":  0, // 预约天数
          "total_cost": 0, // 费用总计
          "homestay_orders_id": 0,
				},

				// 表单字段
				form: {
						"merchant_users": 0, // 商家用户
							"name_of_homestay":  '', // 民宿名称
							"types_of_homestays":  '', // 民宿类型
							"homestay_deposit":  0, // 民宿押金
							"daily_price_of_homestay":  0, // 民宿日价
							"ordinary_users": 0, // 普通用户
							"user_name":  '', // 用户姓名
							"time_of_appointment": new Date().getTime(),
							"appointment_days":  0, // 预约天数
							"total_cost": 0, // 费用总计
						"homestay_orders_id": 0,
				},
				disabledObj:{
          "merchant_users_isDisabled": false,
          "name_of_homestay_isDisabled": false,
          "types_of_homestays_isDisabled": false,
          "ordinary_users_isDisabled": false,
          "user_name_isDisabled": false,
          "time_of_appointment_isDisabled": false,
        },
        // 用户列表
				list_user_merchant_users: [],
        // 用户列表
				list_user_ordinary_users: [],
				// ID字段
				field: "homestay_orders_id",

			}
		},
		methods: {
																																																																																			/**
				 * 提交前事件
				 * @param {Object} param 提交参数
				 */
				submit_before: function(param) {
					// console.log('提交前事件', param);
					// 保存计算结果
																																																																																																																					this.set_total_cost()
																param = this.form
					// 循环参数
					for(var key in param){
						// 错误回调
						try{
							var value = param[key];
							// 值判断与值校验
							console.log("键 ,值 ,类型" ,key ,value ,value instanceof Date);
							if(value && value instanceof Date){
								param[key] = this.$toTime(value ,"yyyy-MM-dd hh:mm:ss");
							}
						}
						catch(err){
							console.log(key ,"转日期错误：" ,err ,"收到请无视!");
						}
					}
					return param;
				},
						formatDateValue(value) {
		  const date = new Date(value);
		  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
		},
		async submit(param, func){
      if (!param) {
        param = this.form;
      }
      var pm = this.events("submit_before", Object.assign({}, param)) || param;
      var msg = await this.events("submit_check", pm);
      var ret;
      if (msg) {
      this.$toast(msg, 'danger');
      } else {
      ret = this.events("submit_main", pm, func);
      }
      return ret;
		},

      /**
       * 提交前验证事件
       * @param {Object} 请求参数
       * @return {String} 验证成功返回null, 失败返回错误提示
       */
            submit_check(param) {
      																																						if (!param.time_of_appointment){
			return "预约时间不能为空";
		}
															        return null;
      },
					/**
			 * 获取商家用户用户列表
			 */
			async get_list_user_merchant_users() {
				var json = await this.$get("~/api/user/get_list?user_group=商家用户");
				if(json.result && json.result.list){
					this.list_user_merchant_users = json.result.list;
				}
				else if(json.error){
					console.error(json.error);
				}
			},





						/**
			 * 获取普通用户用户列表
			 */
			async get_list_user_ordinary_users() {
				var json = await this.$get("~/api/user/get_list?user_group=普通用户");
				if(json.result && json.result.list){
					this.list_user_ordinary_users = json.result.list;
				}
				else if(json.error){
					console.error(json.error);
				}
			},
					async get_user_session_ordinary_users(){
				var _this = this;
				var json = await this.$get("~/api/user_group/get_obj?name=普通用户");
				if(json.result && json.result.obj){
					var source_table = json.result.obj.source_table;
					var user_id = _this.$store.state.user.user_id;
					if (user_id){
						var url = "~/api/"+source_table+"/get_obj?"
						this.$get(url, {"user_id":_this.$store.state.user.user_id}, function(res) {
							if (res.result && res.result.obj) {
								var arr = []
								for (let key in res.result.obj) {
									arr.push(key)
								}
								var arrForm = []
								for (let key in _this.form) {
									arrForm.push(key)
								}
								_this.form["ordinary_users"] = user_id
								_this.disabledObj['ordinary_users' + '_isDisabled'] = true
								for (var i=0;i<arr.length;i++){
                  if (arr[i]!=='examine_state' && arr[i]!=='examine_reply') {
                    for (var j = 0; j < arrForm.length; j++) {
                      if (arr[i] === arrForm[j]) {
                        if (arr[i] !== "ordinary_users") {
                          _this.form[arrForm[j]] = res.result.obj[arr[i]]
                          _this.disabledObj[arrForm[j] + '_isDisabled'] = true
                          break;
                        }
                      }
                    }
                  }
								}
							}
						});
					}
				}
				else if(json.error){
					console.error(json.error);
				}
			},





									set_total_cost(){
				this.form.total_cost = parseFloat(this.form.daily_price_of_homestay) * parseFloat(this.form.appointment_days)
        let r = /^\+?[1-9][0-9]*$/; // 正整数
        if(!r.test(this.form.total_cost) ){
          this.form.total_cost = this.form.total_cost.toFixed(2);
        }
			},
							// 自动计算精度处理
		toFixed: function(num){
			if (!isNaN(num)) {
				return ((num + '').indexOf('.') == -1) ? num : num.toFixed(2);
			}
		},
		  		get_user_info(name,id){
				var obj = null;
  				  if (name == 'merchant_users'){
					  obj = this.list_user_merchant_users.getObj({"user_id":id});
				  }
            				  if (name == 'ordinary_users'){
					  obj = this.list_user_ordinary_users.getObj({"user_id":id});
				  }
          				var ret = "";
				if(obj){
				  ret = obj.nickname+"-"+obj.username;
				}
				return ret;
			},
			/**
			 * 修改文件
			 * @param { Object } files 上传文件对象
			 * @param { String } str 表单的属性名
			 */
			change_file(files, str) {
				var form = new FormData();
				form.append("file", files[0]);
				this.$post("~/api/homestay_orders/upload?", form, (res) => {
					if (res.result) {
						this.form[str] = res.result.url;
					} else if (res.error) {
						this.$toast(res.error.message);
					}
				});
			},

			/**
			 * 修改文件
			 * @param { Object } files 上传文件对象
			 * @param { String } str 表单的属性名
			 */
			change_file_multiple(files, str) {
				let _this = this;
				var form = new FormData();
				for (var i = 0; i < files.length; i++) {
					form.set("file", files[i]);
					_this.$post("~/api/homestay_orders/upload?", form, (res) => {
						if (res.result) {
							if (_this.form[str].length > 0) {
								_this.form[str].push(res.result.url);
							} else {
								_this.form[str] = [res.result.url];
							}
						} else if (res.error) {
							_this.$toast(res.error.message);
						}
					});
				}
			},

			/**
			 * 获取对象后获取缓存表单
			 * @param {Object} json
			 * @param {Object} func
			 */
			get_obj_before(param){
				var form = $.db.get("form");
				// if (form) {
        //   delete(form.examine_state)
        //   delete(form.examine_reply)
        //   this.obj = $.push(this.obj ,form);
				// 	this.form = $.push(this.form ,form);
				// }
				// var arr = []
				// for (let key in form) {
				// 	arr.push(key)
				// }
				// for (var i=0;i<arr.length;i++){
				// 	this.disabledObj[arr[i] + '_isDisabled'] = true
				// }
        if (form) {
          var arr = []
          for (let key in form) {
            arr.push(key)
          }
          var arrForm = []
          for (let key in this.form) {
            arrForm.push(key)
          }
          for (var i=0;i<arr.length;i++){
            if (arr[i]!=='examine_state' && arr[i]!=='examine_reply') {
              for (var j = 0; j < arrForm.length; j++) {
                if (arrForm[j] === arr[i]) {
                  this.form[arrForm[j]] = form[arr[i]]
                  this.obj[arrForm[j]] = form[arr[i]]
                  this.disabledObj[arrForm[j] + '_isDisabled'] = true
                  break;
                }
              }
			  if(arr[i] === "source_table"){
			  	this.form['source_table'] = form[arr[i]]
			  }
			  if(arr[i] === "source_id"){
			  	this.form['source_id'] = form[arr[i]]
			  }
			  if(arr[i] === "source_user_id"){
			  	this.form['source_user_id'] = form[arr[i]]
			  }
            }
          }
        }
																							        if (this.form["time_of_appointment"] && JSON.stringify(this.form["time_of_appointment"]).indexOf("-")===-1) {
          this.form["time_of_appointment"] = this.$toTime(parseInt(this.form["time_of_appointment"]), "yyyy-MM-dd")
        }

        $.db.del("form");
				return param;
			},

			/**
			 * 获取对象后获取缓存表单
			 * @param {Object} json
			 * @param {Object} func
			 */
			get_obj_after(json ,func){
				// var form = $.db.get("form");
				// var obj = Object.assign({} ,form ,this.obj);
				// if (obj) {
        //   delete(obj.examine_state)
        //   delete(obj.examine_reply)
				// 	this.obj = $.push(this.obj ,obj);
				// }
				// if (form) {
        //   delete(form.examine_state)
        //   delete(form.examine_reply)
				// 	this.form = $.push(this.form ,form);
				// }

				if(func){
					func(json);
				}
			},

		},
		created() {
						this.get_list_user_merchant_users();
																		this.get_user_session_ordinary_users();
					this.get_list_user_ordinary_users();
															},
	}
</script>

<style>
	.diy_compute{
		line-height: 40px;
	}
	.diy_field.diy_img_multiple{
		margin: 0;
	}
	.diy_field.diy_img_multiple div{
		float: left;
		position: relative;
		margin: 0 10px 10px 0;
	}
	.diy_field.diy_img_multiple img{
		height: 100px;
		width: auto;
	}
	.diy_field.diy_img_multiple span{
		position: absolute;
		top: 5px;
		right: 5px;
		width: 20px;
		height: 20px;
		background: #0000008a;
		color: #fff;
		line-height: 20px;
		text-align: center;
		border-radius: 100%;
		cursor: pointer;
	}



</style>
